using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace EntityKit.Runtime
{
    public class EntityLauncher : MonoBehaviour
    {
        public enum InitializationOpportunity
        {
            Auto,
            Custom
        }

        [SerializeField] private InitializationOpportunity mInitializationOpportunity = InitializationOpportunity.Auto;

        /// <summary>
        /// Editor 完成注入，切勿代码中操作
        /// </summary>
        [SerializeField] private List<Component> mSceneEntityComponents = new List<Component>();

        private bool mInitializationComplete = false;

        /// <summary>
        /// 获取初始化状态
        /// </summary>
        public bool IsInitializationComplete() => mInitializationComplete;

        private void Start()
        {
            if (mInitializationOpportunity == InitializationOpportunity.Auto)
            {
                InitializeEntityKit();
            }
        }
        
        /// <summary>
        /// 手动触发实体初始化
        /// </summary>
        public void ManualInitialize()
        {
            if (mInitializationOpportunity == InitializationOpportunity.Custom && !mInitializationComplete)
            {
                InitializeEntityKit();
            }
        }


        private void Update()
        {
            UpdateEntityKit();
        }

        private void OnDestroy()
        {
            ReleaseEntityKit();
        }
        
        /// <summary>
        /// 批量初始化所有实体
        /// </summary>
        private void InitializeEntityKit()
        {
            if (mInitializationComplete)
                return;
            var initializedEntities = new List<IEntity>();
            foreach (var component in mSceneEntityComponents)
            {
                if (component != null && component is IEntity entity)
                    initializedEntities.Add(entity);
            }
            EntityManager.Initialized(initializedEntities);
            mInitializationComplete = true;
        }

        private void UpdateEntityKit()
        {
            if (!mInitializationComplete)
                return;
            EventKit.Update();
            EntityManager.Update();
        }


        /// <summary>
        /// 释放所有实体
        /// </summary>
        private void ReleaseEntityKit()
        {
            if (!mInitializationComplete)
                return;
            EntityManager.Release();
            EventKit.Release();
            mInitializationComplete = false;
        }





    }
}